package com.library.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.library.common.base.ApiResult;
import com.library.entity.*;
import com.library.entity.vo.UserInfoToken;
import com.library.entity.vo.WechatLoginDto;
import com.library.entity.vo.WechatLoginDto1;
import com.library.service.*;
import com.library.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.*;


/**
 * @Description: 首页产品
 * @Author:mengyangguang
 * @CreateDate:2022/9/27
 **/
@Slf4j
@RestController
@RequestMapping("/userInfo")
@SuppressWarnings("unchecked")
@CrossOrigin(allowCredentials = "true")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoSService;
    @Autowired
    private ObpCityService obpCityService;
    @Autowired
    private ObpAreaService obpAreaService;
    @Autowired
    private ObpCommitteeService obpCommitteeService;
    @Autowired
    private ObjStreetService objStreetService;
    @Autowired
    private WechatLoginService wechatLoginService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private BookUserService bookUserService;
    @Autowired
    private UserLoginBrowsingLogService userLoginBrowsingLogService;

    /**
     * 微信扫码授权接口
     */
    @ApiOperation("授权登录")
    @PostMapping(value = "/wxlogin")
    public ApiResult<UserInfo> list(@RequestBody LoginBean param) throws IOException {
        //先根据传的code 获取openid
        if(TextUtils.isEmpty(param.getCode()))
        {
            return ApiResult.ok(null);
        }
        String wxOpenid = WxUntilln.getWxOpenid(param.getCode());
        //查找openid
        if(TextUtils.isEmpty(wxOpenid))
        {
            return ApiResult.ok(null);
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getOpenId, wxOpenid);
        String location = param.getLocation();
        if (TextUtils.isEmpty(location)) {
            location = "410102001002";
        }
        if (!TextUtils.isEmpty(location)) {
            if (userInfoSService.getOne(queryWrapper) == null) {
                //插入数据库
                UserInfo userInfoS = new UserInfo();
                userInfoS.setOpenId(wxOpenid);
                userInfoS.setCityCode(location.substring(0, 4));
                userInfoS.setAreaCode(location.substring(0, 6));
                userInfoS.setStreetCode(location.substring(0, 9));
                userInfoS.setCommitteeCode(location);
                userInfoS.setProvinceName("河南省");
                LambdaQueryWrapper<ObpCityEntity> obpCityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpCityLambdaQueryWrapper.eq(ObpCityEntity::getCityCode, location.substring(0, 4));
                userInfoS.setCityName(obpCityService.getOne(obpCityLambdaQueryWrapper).getCityName());
                LambdaQueryWrapper<ObpAreaEntity> obpAreaLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpAreaLambdaQueryWrapper.eq(ObpAreaEntity::getAreaCode, location.substring(0, 6));
                userInfoS.setAreaName(obpAreaService.getOne(obpAreaLambdaQueryWrapper).getAreaName());
                LambdaQueryWrapper<ObjStreetEntity> objStreetLambdaQueryWrapper = new LambdaQueryWrapper<>();
                objStreetLambdaQueryWrapper.eq(ObjStreetEntity::getStreetCode, location.substring(0, 9));
                userInfoS.setStreetName(objStreetService.getOne(objStreetLambdaQueryWrapper).getStreetName());
                LambdaQueryWrapper<ObpCommitteeEntity> obpCommitteeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpCommitteeLambdaQueryWrapper.eq(ObpCommitteeEntity::getCommitteeCode, location);
                userInfoS.setCommitteeName(obpCommitteeService.getOne(obpCommitteeLambdaQueryWrapper).getCommitteeName());
                //userInfoS.setUserId(Common1Util.getId());
                userInfoS.setUserId(Common1Util.getId1());
                userInfoS.setNick("用户" + userInfoS.getUserId());
                userInfoSService.save(userInfoS);
                //同时向bookuser表里面插入数据
                BookUserEntity bookUserEntity = new BookUserEntity();
                bookUserEntity.setUserName(userInfoS.getUserId() + "");
                bookUserEntity.setUserCode(userInfoS.getUserId() + "");
                bookUserEntity.setProvince("河南省");
                bookUserEntity.setStatus("1");
                bookUserEntity.setUseStatus("1");
                LocalDateTime date = LocalDateTime.now();
                bookUserEntity.setCreateTime(date);
                bookUserEntity.setJurisdiction("6");
                bookUserEntity.setCity(location.substring(0, 4));
                bookUserEntity.setDistrict(location.substring(0, 6));
                bookUserEntity.setCommittee(location);
                bookUserEntity.setVillage(location.substring(0, 9));
                bookUserService.saveUser(bookUserEntity);
            } else {
                //更新数据库
                UserInfo one = userInfoSService.getOne(queryWrapper);
                one.setCityCode(location.substring(0, 4));
                one.setAreaCode(location.substring(0, 6));
                one.setStreetCode(location.substring(0, 9));
                one.setCommitteeCode(location);
                one.setProvinceName("河南省");
                LambdaQueryWrapper<ObpCityEntity> obpCityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpCityLambdaQueryWrapper.eq(ObpCityEntity::getCityCode, location.substring(0, 4));
                one.setCityName(obpCityService.getOne(obpCityLambdaQueryWrapper).getCityName());
                LambdaQueryWrapper<ObpAreaEntity> obpAreaLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpAreaLambdaQueryWrapper.eq(ObpAreaEntity::getAreaCode, location.substring(0, 6));
                one.setAreaName(obpAreaService.getOne(obpAreaLambdaQueryWrapper).getAreaName());
                LambdaQueryWrapper<ObjStreetEntity> objStreetLambdaQueryWrapper = new LambdaQueryWrapper<>();
                objStreetLambdaQueryWrapper.eq(ObjStreetEntity::getStreetCode, location.substring(0, 9));
                one.setStreetName(objStreetService.getOne(objStreetLambdaQueryWrapper).getStreetName());
                LambdaQueryWrapper<ObpCommitteeEntity> obpCommitteeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpCommitteeLambdaQueryWrapper.eq(ObpCommitteeEntity::getCommitteeCode, location);
                one.setCommitteeName(obpCommitteeService.getOne(obpCommitteeLambdaQueryWrapper).getCommitteeName());
                userInfoSService.update(one, queryWrapper);
                LambdaQueryWrapper<BookUserEntity> bookUserEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                bookUserEntityLambdaQueryWrapper.eq(BookUserEntity::getUserCode, one.getUserId());
                if (bookUserService.getOne(bookUserEntityLambdaQueryWrapper) != null) {
                    BookUserEntity one1 = bookUserService.getOne(bookUserEntityLambdaQueryWrapper);
                    one1.setCity(one.getCityCode());
                    one1.setDistrict(one.getAreaCode());
                    one1.setCommittee(one.getCommitteeCode());
                    one1.setVillage(one.getStreetCode());
                    bookUserService.updateById(one1);
                }

            }
        }
        UserInfo one = userInfoSService.getOne(queryWrapper);
        //jwt生成token
        UserInfoToken userInfoToken = new UserInfoToken();
        userInfoToken.setId(one.getId());
        userInfoToken.setUserId(one.getUserId());
        userInfoToken.setUserName(one.getUserName());
        userInfoToken.setMobile(one.getPhone());
        String token = jwtTokenUtil.createToken(userInfoToken);
        one.setToken(token);
        one.setProvinceName(one.getProvinceName() + one.getCityName() + one.getAreaName()+one.getCommitteeName());
        return ApiResult.ok(one);
    }

    /**
     * 微信扫码授权接口
     */
    @ApiOperation("获取用户信息")
    @PostMapping(value = "/getUserInfo")
    public ApiResult<UserInfo> getUserInfo(@RequestBody LoginBean param) throws IOException {
        //先根据传的code 获取openid
        if(TextUtils.isEmpty(param.getCode()))
        {
            return ApiResult.ok(null);
        }
        String wxOpenid = WxUntill.getWxOpenid(param.getCode());
        if(TextUtils.isEmpty(wxOpenid))
        {
            return ApiResult.ok(null);
        }
        //查找openid
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getOpenId, wxOpenid);
        UserInfo one = userInfoSService.getOne(queryWrapper);
        return ApiResult.ok(one);
    }

    /**
     * 微信扫码授权接口
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/getOpenId/{code}")
    public ApiResult<UserInfo> getUserInfo(@PathVariable("code") String code) {
        if(TextUtils.isEmpty(code))
        {
            return ApiResult.ok(null);
        }
        try {
            String wxOpenid = WxUntill.getWxOpenid(code);
            if(TextUtils.isEmpty(wxOpenid))
            {
                return ApiResult.ok(null);
            }
            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getOpenId, wxOpenid);
            UserInfo one = userInfoSService.getOne(wrapper);
            if (one == null) {
                //注册
                //插入数据库
                String location = "410102001002";
                UserInfo userInfoS = new UserInfo();
                userInfoS.setOpenId(wxOpenid);
                userInfoS.setCityCode(location.substring(0, 4));
                userInfoS.setAreaCode(location.substring(0, 6));
                userInfoS.setStreetCode(location.substring(0, 9));
                userInfoS.setCommitteeCode(location);
                userInfoS.setProvinceName("河南省");
                LambdaQueryWrapper<ObpCityEntity> obpCityLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpCityLambdaQueryWrapper.eq(ObpCityEntity::getCityCode, location.substring(0, 4));
                userInfoS.setCityName(obpCityService.getOne(obpCityLambdaQueryWrapper).getCityName());
                LambdaQueryWrapper<ObpAreaEntity> obpAreaLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpAreaLambdaQueryWrapper.eq(ObpAreaEntity::getAreaCode, location.substring(0, 6));
                userInfoS.setAreaName(obpAreaService.getOne(obpAreaLambdaQueryWrapper).getAreaName());
                LambdaQueryWrapper<ObjStreetEntity> objStreetLambdaQueryWrapper = new LambdaQueryWrapper<>();
                objStreetLambdaQueryWrapper.eq(ObjStreetEntity::getStreetCode, location.substring(0, 9));
                userInfoS.setStreetName(objStreetService.getOne(objStreetLambdaQueryWrapper).getStreetName());
                LambdaQueryWrapper<ObpCommitteeEntity> obpCommitteeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                obpCommitteeLambdaQueryWrapper.eq(ObpCommitteeEntity::getCommitteeCode, location);
                userInfoS.setCommitteeName(obpCommitteeService.getOne(obpCommitteeLambdaQueryWrapper).getCommitteeName());
                //userInfoS.setUserId(Common1Util.getId());
                userInfoS.setUserId(Common1Util.getId1());
                userInfoS.setNick("用户" + userInfoS.getUserId());
                userInfoSService.save(userInfoS);
                //同时向bookuser表里面插入数据
                BookUserEntity bookUserEntity = new BookUserEntity();
                bookUserEntity.setUserName(userInfoS.getUserId() + "");
                bookUserEntity.setUserCode(userInfoS.getUserId() + "");
                bookUserEntity.setProvince("河南省");
                bookUserEntity.setStatus("1");
                bookUserEntity.setUseStatus("1");
                LocalDateTime date = LocalDateTime.now();
                bookUserEntity.setCreateTime(date);
                bookUserEntity.setJurisdiction("6");
                bookUserEntity.setCity("4101");
                bookUserEntity.setDistrict("410102");
                bookUserEntity.setCommittee("410102001002");
                bookUserEntity.setVillage("410102001");
                bookUserService.saveUser(bookUserEntity);
                userInfoS.setProvinceName(userInfoS.getProvinceName() + userInfoS.getCityName() + userInfoS.getAreaName()+userInfoS.getCommitteeName());
                return ApiResult.ok(userInfoS);
            } else {
                one.setProvinceName(one.getProvinceName() + one.getCityName() + one.getAreaName()+one.getCommitteeName());
                //向登录日志表里插入数据
                UserLoginBrowsingLog log=new UserLoginBrowsingLog();
                log.setOpenId(wxOpenid);
                log.setReferrerUrl("app");
                log.setCreatedAt(new Date());
                log.setProvince("41");
                log.setCity(one.getCityCode());
                log.setArea(one.getAreaCode());
                log.setCommittee(one.getCommitteeCode());
                log.setStreet(one.getStreetCode());
                userLoginBrowsingLogService.save(log);
                return ApiResult.ok(one);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //上传头像返回链接
    //@Resource(name = "oss")
    private OSS oss;

    //@Value("${aliyun.oss.bucket}")
    private String bucket;
    //@Value("${aliyun.oss.endpoint}")
    private String endpoint;

    /**
     * 上传后 url点击是查看
     *
     * @param file
     * @return
     */
    @PostMapping("/pic/upload")
    @ResponseBody
    public ApiResult<String> getAwsS3Path(@RequestParam(value = "file", required = true) MultipartFile file) {
        String fileName = file.getOriginalFilename();
        log.info("/file/oss/upload; file-name={}", fileName);
        String filePath = filePath(fileName);
        try {
            InputStream instream = file.getInputStream();
            ObjectMetadata objectMetadata = objectMetadata(fileName, instream);
            oss.putObject(bucket, filePath, instream, objectMetadata);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            oss.shutdown();
        }
        String url = new StringBuilder().append("https://" + bucket + "." + endpoint + "/" + filePath).toString();
        log.info("file-oss result url={}", url);
        return ApiResult.ok(url);
    }

    private static String filePath(String fileName) {
        return UUID.randomUUID().toString() + fileName.subSequence(fileName.lastIndexOf("."), fileName.length());
    }

    private ObjectMetadata objectMetadata(String fileName, InputStream instream) throws IOException {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(instream.available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(getcontentType(fileName));
        objectMetadata.setContentDisposition("inline;filename*=utf-8'zh_cn'" + fileName);
        objectMetadata.setHeader("Content-disposition", "filename*=utf-8'zh_cn'" + fileName);
        return objectMetadata;
    }

    //修改用户昵称和头像

    /**
     * 微信扫码授权接口
     */
    @ApiOperation("修改用户昵称或头像")
    @PostMapping(value = "/updateUser")
    public ApiResult<UserInfo> updateUser(@RequestBody LoginBean param) throws IOException {
        //先根据传的code 获取openid
        if(TextUtils.isEmpty(param.getCode()))
        {
            return ApiResult.ok(null);
        }
        String wxOpenid = WxUntill.getWxOpenid(param.getCode());
        //查找openid
        if(TextUtils.isEmpty(wxOpenid))
        {
            return ApiResult.ok(null);
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getOpenId, wxOpenid);
        UserInfo one = userInfoSService.getOne(queryWrapper);
        if (userInfoSService.getOne(queryWrapper) == null) {
            return ApiResult.ok(null);
        } else {
            if (!TextUtils.isEmpty(param.getNickName())) {
                one.setNick(param.getNickName());
                //修改用户表名称
                LambdaQueryWrapper<BookUserEntity> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(BookUserEntity::getUserCode, one.getUserId());
                List<BookUserEntity> list = bookUserService.list(queryWrapper1);
                if (list != null && list.size() == 1) {
                    BookUserEntity bookUserEntity = list.get(0);
                    bookUserEntity.setUserName(param.getNickName());
                    bookUserService.updateById(bookUserEntity);
                }
            }
            if (!TextUtils.isEmpty(param.getNickUrl()) && param.getNickUrl().contains("http")) {
                one.setPhotoUrl(param.getNickUrl());
            }
            userInfoSService.update(one, queryWrapper);
        }
        return ApiResult.ok(one);
    }

    /**
     * @param filenameExtension
     * @return contentType
     */
    public static String getcontentType(String filenameExtension) {
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".bmp")) {
            return "image/bmp";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".gif")) {
            return "image/gif";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".jpeg")
                || StringUtils.endsWithIgnoreCase(filenameExtension, ".jpg")
                || StringUtils.endsWithIgnoreCase(filenameExtension, ".png")) {
            return "image/jpg";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".html")) {
            return "text/html";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".txt")) {
            return "text/plain";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".vsd")) {
            return "application/vnd.visio";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".pptx")
                || StringUtils.endsWithIgnoreCase(filenameExtension, ".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".docx")
                || StringUtils.endsWithIgnoreCase(filenameExtension, ".doc")) {
            return "application/msword";
        }
        if (StringUtils.endsWithIgnoreCase(filenameExtension, ".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

    /**
     * 生成二维码并返回给前端
     */
    @ApiOperation("生成二维码")
    @PostMapping(value = "/generateQrCode")
    public ApiResult<String> generateQrCode(@RequestBody WechatLoginDto wechatLoginDto) throws CustomizeException {
        //先生成时间戳并存入数据库
        WechatLogin wechatLogin = new WechatLogin();
        wechatLogin.setTimeStamp(wechatLoginDto.getTimeStamp());
        wechatLogin.setStatus(0);
        wechatLoginService.save(wechatLogin);
        String wxCode = getWXCode("Tiao" + wechatLoginDto.getTimeStamp());
        return ApiResult.ok(wxCode);
    }

    /**
     * 获取扫码状态
     */
    @ApiOperation("获取扫码状态")
    @PostMapping(value = "/getStatus")
    public ApiResult<Integer> getStatus(@RequestBody WechatLoginDto wechatLoginDto) throws CustomizeException {
        LambdaQueryWrapper<WechatLogin> loginLambdaQueryWrapper = new LambdaQueryWrapper<>();
        loginLambdaQueryWrapper.eq(WechatLogin::getTimeStamp, wechatLoginDto.getTimeStamp());
        WechatLogin one = wechatLoginService.getOne(loginLambdaQueryWrapper);
        if (one == null) {
            return ApiResult.failed("无法识别");
        }
        return ApiResult.ok(one.getStatus());
    }

    /**
     * 根据时间戳获取用户信息
     */
    @ApiOperation("根据时间戳获取用户信息")
    @PostMapping(value = "/getTimeStampUserInfo")
    public ApiResult<UserInfo> getTimeStampUserInfo(@RequestBody WechatLoginDto wechatLoginDto) throws CustomizeException {
        LambdaQueryWrapper<WechatLogin> loginLambdaQueryWrapper = new LambdaQueryWrapper<>();
        loginLambdaQueryWrapper.eq(WechatLogin::getTimeStamp, wechatLoginDto.getTimeStamp());
        WechatLogin one = wechatLoginService.getOne(loginLambdaQueryWrapper);
        if (one == null) {
            return ApiResult.failed("无法识别");
        }
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getOpenId, one.getOpenId());
        UserInfo one1 = userInfoSService.getOne(userInfoLambdaQueryWrapper);
        if (one1 == null) {
            return ApiResult.failed("暂无用户信息");
        }
        return ApiResult.ok(one1);
    }

    /**
     * 小程序扫描二维码
     */
    @ApiOperation("小程序扫描二维码")
    @PostMapping(value = "/sanQRCode")
    public ApiResult<Boolean> sanQRCode(@RequestBody WechatLoginDto wechatLoginDto) throws CustomizeException {
        LambdaQueryWrapper<WechatLogin> loginLambdaQueryWrapper = new LambdaQueryWrapper<>();
        loginLambdaQueryWrapper.eq(WechatLogin::getTimeStamp, wechatLoginDto.getTimeStamp());
        WechatLogin one = wechatLoginService.getOne(loginLambdaQueryWrapper);
        if (one == null) {
            return ApiResult.failed("无法识别");
        }
        one.setStatus(1);
        return ApiResult.ok(wechatLoginService.updateById(one));
    }

    /**
     * 小程序授权登录
     */
    @ApiOperation("小程序授权登录")
    @PostMapping(value = "/authorize")
    public ApiResult<UserInfo> authorize(@RequestBody WechatLoginDto1 wechatLoginDto) throws CustomizeException {
        LambdaQueryWrapper<WechatLogin> loginLambdaQueryWrapper = new LambdaQueryWrapper<>();
        loginLambdaQueryWrapper.eq(WechatLogin::getTimeStamp, wechatLoginDto.getTimeStamp());
        WechatLogin one = wechatLoginService.getOne(loginLambdaQueryWrapper);
        if (one == null) {
            return ApiResult.failed("无法识别");
        }
        one.setOpenId(wechatLoginDto.getOpenId());
        one.setStatus(2);
        wechatLoginService.updateById(one);
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getOpenId, wechatLoginDto.getOpenId());
        if (userInfoSService.getOne(queryWrapper) == null) {
            String location = "410102001002";
            UserInfo userInfoS = new UserInfo();
            userInfoS.setOpenId(wechatLoginDto.getOpenId());
            userInfoS.setCityCode(location.substring(0, 4));
            userInfoS.setAreaCode(location.substring(0, 6));
            userInfoS.setStreetCode(location.substring(0, 9));
            userInfoS.setCommitteeCode(location);
            userInfoS.setProvinceName("河南省");
            LambdaQueryWrapper<ObpCityEntity> obpCityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            obpCityLambdaQueryWrapper.eq(ObpCityEntity::getCityCode, location.substring(0, 4));
            userInfoS.setCityName(obpCityService.getOne(obpCityLambdaQueryWrapper).getCityName());
            LambdaQueryWrapper<ObpAreaEntity> obpAreaLambdaQueryWrapper = new LambdaQueryWrapper<>();
            obpAreaLambdaQueryWrapper.eq(ObpAreaEntity::getAreaCode, location.substring(0, 6));
            userInfoS.setAreaName(obpAreaService.getOne(obpAreaLambdaQueryWrapper).getAreaName());
            LambdaQueryWrapper<ObjStreetEntity> objStreetLambdaQueryWrapper = new LambdaQueryWrapper<>();
            objStreetLambdaQueryWrapper.eq(ObjStreetEntity::getStreetCode, location.substring(0, 9));
            userInfoS.setStreetName(objStreetService.getOne(objStreetLambdaQueryWrapper).getStreetName());
            LambdaQueryWrapper<ObpCommitteeEntity> obpCommitteeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            obpCommitteeLambdaQueryWrapper.eq(ObpCommitteeEntity::getCommitteeCode, location);
            userInfoS.setCommitteeName(obpCommitteeService.getOne(obpCommitteeLambdaQueryWrapper).getCommitteeName());
            //userInfoS.setUserId(Common1Util.getId());
            userInfoS.setUserId(Common1Util.getId1());
            userInfoS.setNick("用户" + userInfoS.getUserId());
            userInfoSService.save(userInfoS);
            return ApiResult.ok(userInfoS);
        }else{
            UserInfo one1 = userInfoSService.getOne(queryWrapper);
            //向登录日志表里插入数据
            UserLoginBrowsingLog log=new UserLoginBrowsingLog();
            log.setOpenId(one1.getOpenId());
            log.setReferrerUrl("H5");
            log.setCreatedAt(new Date());
            log.setProvince("41");
            log.setCity(one1.getCityCode());
            log.setArea(one1.getAreaCode());
            log.setCommittee(one1.getCommitteeCode());
            log.setStreet(one1.getStreetCode());
            userLoginBrowsingLogService.save(log);

        }
        return ApiResult.ok(userInfoSService.getOne(queryWrapper));
    }

    /**
     * 获取小程序菊花码
     * parm：machineNo    二维码想携带的参数
     **/
    public static String getWXCode(String machineNo) throws CustomizeException {
        String appId = "wxe3f54ea3cdf72bd7";   //自己小程序的appid
        String secret = "a45249c20fe822781142e20d92014588";   //自己小程序的密钥
        String aiyunUrl = "";
        try {
            //这里调用的是上面的获取access_token方法
            String access_token = getWxAcesstoken(appId, secret);

            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            String scene = machineNo;  //携带参数放在scene 内
            Map<String, String> param = new HashMap<>();
            param.put("scene", scene);
            //这里的page如果没有的话可以不写，默认是跳主页，如果写了没有的页面的话，会返回错误信息
//            param.put("page", "pages/index/index");
            String json = JSON.toJSONString(param);
            ByteArrayInputStream inputStream = sendPost(url, json);
            //这里判断的是返回的图片还是错误信息，一般错误信息不会大于200

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int i;
            byte[] buffer = new byte[200];
            while ((i = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, i);
            }
//                String str = new String(byteArrayOutputStream.toByteArray());
//                //错误信息的格式在官方文档里有
//                JSONObject jsonObject = JSONObject.parseObject(str);
//                if ("41030".equals(jsonObject.getString("errcode"))) {
//                    System.out.println("所传page页面不存在，或者小程序没有发布");
//                    throw new CustomizeException("所传page页面不存在，或者小程序没有发布");
//                } else if ("45009".equals(jsonObject.getString("errcode"))) {
//                    System.out.println("调用分钟频率受限");
//                    throw new CustomizeException("调用分钟频率受限");
//                }
            byte[] bytes = byteArrayOutputStream.toByteArray();
            aiyunUrl = Base64.getEncoder().encodeToString(bytes);
            byteArrayOutputStream.close();


//            //上传阿里云，也可以不上传
////            String aiyunUrl= ossClientUtil.UploadImgAndReturnImgUrlInputStream(inputStream, fileName, path);
//            //输出到本地的代码
//            FileOutputStream fileOutputStream = new FileOutputStream("D://电子书/mengyangguang/ercode.png");
//            int i;
//            byte[] buffer = new byte[200];
//            while ((i = inputStream.read(buffer)) != -1) {
//                fileOutputStream.write(buffer, 0, i);
//            }
//            fileOutputStream.flush();
//            fileOutputStream.close();
//
//            inputStream.close();
//            System.out.println("二维码生成成功");
        } catch (Exception e) {
            System.out.println("获取二维码异常");
            throw new CustomizeException(e.getMessage());
        }
        return aiyunUrl;
    }

    public static class CustomizeException extends Exception {

        public CustomizeException(String message) {
            super(message);
        }
    }

    public static ByteArrayInputStream sendPost(String URL, String json) {
        InputStream inputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
//        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.addHeader("Content-type", "application/x-javascript; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                // 创建一个Buffer字符串
                byte[] buffer = new byte[1024];
                // 每次读取的字符串长度，如果为-1，代表全部读取完毕
                int len = 0;
                // 使用一个输入流从buffer里把数据读取出来
                while ((len = inputStream.read(buffer)) != -1) {
                    // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                    outStream.write(buffer, 0, len);
                }
                // 关闭输入流
                inputStream.close();
                // 把outStream里的数据写入内存
                byteArrayInputStream = new ByteArrayInputStream(outStream.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArrayInputStream;
    }

    /**
     * 获取微信accesstoken
     *
     * @param wxappid
     * @param wxappkey
     * @return
     */
    public static String getWxAcesstoken(String wxappid, String wxappkey) throws CustomizeException {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxappid + "&secret=" + wxappkey;

        try {
            String jsonstr = HttpUtil.get(tokenUrl);
            JSONObject jsonObject = JSON.parseObject(jsonstr);
            if (jsonObject.containsKey("access_token")) {
                String accesstoken = jsonObject.getString("access_token");
                return accesstoken;
            } else {
                System.out.println("未获取到token");
                throw new CustomizeException("未获取到token");
            }

        } catch (Exception e) {
            System.out.println("未获取到token");
            throw new CustomizeException(e.getMessage());
        }
    }

}
